import 'package:flutter/material.dart';

import '../utils/follow_api.dart';

class FollowButton extends StatefulWidget {
  final String userId;

  const FollowButton({super.key, required this.userId});

  @override
  State<FollowButton> createState() => _FollowButtonState();
}

class _FollowButtonState extends State<FollowButton> {
  bool _isFollowing = false;
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _loadFollowState();
  }

  Future<void> _loadFollowState() async {
    try {
      final result = await checkIfFollowing(widget.userId);
      if (mounted) {
        setState(() {
          _isFollowing = result;
          _loading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _loading = false;
        });
      }
    }
  }

  Future<void> _toggleFollow() async {
    setState(() {
      _loading = true;
    });
    try {
      if (_isFollowing) {
        await unfollowUser(widget.userId);
      } else {
        await followUser(widget.userId);
      }
      if (mounted) {
        setState(() {
          _isFollowing = !_isFollowing;
          _loading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _loading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_loading) {
      return const SizedBox(
        width: 80,
        height: 32,
        child: Center(child: CircularProgressIndicator(strokeWidth: 2)),
      );
    }

    return ElevatedButton(
      onPressed: _toggleFollow,
      style: ElevatedButton.styleFrom(
        shape: const StadiumBorder(),
        backgroundColor: _isFollowing ? Colors.grey[300] : Colors.redAccent,
        foregroundColor: _isFollowing ? Colors.black87 : Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
        minimumSize: const Size(80, 32),
      ),
      child: Text(_isFollowing ? '已关注' : '关注'),
    );
  }
}
